package com.uzai.console.service.wechatwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.dto.device.DeviceInfoBaseCache;
import com.uzai.common.dto.device.DeviceInfoMobileWxWorkCacheDto;
import com.uzai.common.dto.device.DeviceInfoWxWorkCacheDto;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.Math;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.device.deviceauth.DeviceAuthQuery;
import com.uzai.console.dto.rocketmq.androidapp.UpdateAndroidAppDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.CloseClientAppDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.UpdateClientAppDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatRecvmsgTypeDto;
import com.uzai.console.dto.wechatwork.devicewxworkinfo.*;
import com.uzai.console.entity.*;
import com.uzai.console.enums.*;
import com.uzai.console.jsonvo.merbaseconfig.RealNameVerificationJson;
import com.uzai.console.mapper.*;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.deviceauth.DeviceAuthService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoCardPayService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoSyncService;
import com.uzai.console.service.wechatwork.DeviceWxworkInfoService;
import com.uzai.console.service.wechatwork.WxWorkGroupService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.vo.alarm.alarmrule.AlarmRuleInfoVo;
import com.uzai.console.vo.alipaydetail.businessinfo.DeviceAuthBusinessInfo;
import com.uzai.console.vo.deviceauth.DeviceAuthVo;
import com.uzai.console.vo.wechatprivate.devicewechatinfo.CardBuyResult;
import com.uzai.console.vo.wechatprivate.devicewechatinfo.DeviceAmountVo;
import com.uzai.console.vo.wechatwork.devicewxworkinfo.DeviceWxworkInfoAddVo;
import com.uzai.console.vo.wechatwork.devicewxworkinfo.DeviceWxworkInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信机器人
 *
 * @author liuqi
 * @date 2021年08月19日 16:50
 */
@Service
public class DeviceWxworkInfoServiceImpl implements DeviceWxworkInfoService {

    Logger logger = LoggerFactory.getLogger(DeviceWxworkInfoServiceImpl.class);
    @Autowired
    NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private DeviceGroupMapper deviceGroupMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private AlarmRuleMapper alarmRuleMapper;
    @Autowired
    private DeviceVersionMapper deviceVersionMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private DeviceProductMapper deviceProductMapper;
    @Autowired
    private DevicePriceMapper devicePriceMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private DeviceAuthDetailMapper deviceAuthDetailMapper;
    @Autowired
    private AlipayDetailService alipayDetailService;
    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private CdkeysMapper cdkeysMapper;
    @Autowired
    private DeviceWechatInfoCardPayService deviceWechatInfoCardPayService;
    @Autowired
    private DeviceAuthService deviceAuthService;
    @Autowired
    private WxworkContactsService wxworkContactsService;
    @Autowired
    private WxWorkGroupService wxWorkGroupService;
    @Autowired
    private CdkeysMobileAppMapper cdkeysMobileAppMapper;
    @Autowired
    private DeviceWechatInfoSyncService deviceWechatInfoSyncService;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ClientApiService clientApiService;

    /**
     * 查询个人微信列表
     *
     * @param deviceWxworkInfoQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<DeviceWxworkInfoVo> findDeviceWxworkInfoList(DeviceWxworkInfoQuery deviceWxworkInfoQuery) {

        Integer now = DateUtil.getNowTime();

        //手动处理机器人分页查询-如果是机器人昵称，则按照中文gbk排序
        List<OrderItem> orderItemList = deviceWxworkInfoQuery.getOrderItemList();
        if (orderItemList != null && orderItemList.size() > 0) {
            for (OrderItem orderItem : orderItemList) {
                if ("deviceName".equals(orderItem.getColumn())) {
                    orderItem.setColumn(" convert( " + orderItem.getColumn() + " using gbk) ");
                } else if ("deviceRemark".equals(orderItem.getColumn())) {
                    orderItem.setColumn(" convert( " + orderItem.getColumn() + " using gbk) ");
                }
            }
        }

        //新建返回到页面的LIST对象
        List<DeviceWxworkInfoVo> deviceWxworkInfoPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<DeviceWxworkInfo> page = new Page<>();
        deviceWxworkInfoQuery.convert(page);
        ArrayList<DeviceWxworkInfo> deviceWxworkInfoList = deviceWxworkInfoMapper.findListByAuthGroup(page, deviceWxworkInfoQuery);
        if (deviceWxworkInfoList != null && deviceWxworkInfoList.size() > 0) {
            for (DeviceWxworkInfo deviceWxworkInfo : deviceWxworkInfoList) {
                DeviceWxworkInfoVo deviceWxworkInfoPageVo = new DeviceWxworkInfoVo();
                BeanUtils.copyProperties(deviceWxworkInfo, deviceWxworkInfoPageVo);

                //判断接收消息
                if (deviceWxworkInfo.getRecvmsgType() != null) {
                    //移动端接收消息
                    if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId().intValue()) {
                        deviceWxworkInfoPageVo.setPcMsgHandler(0);
                        deviceWxworkInfoPageVo.setMobileMsgHandler(1);
                        //电脑端接收消息
                    } else if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId().intValue()) {
                        deviceWxworkInfoPageVo.setPcMsgHandler(1);
                        deviceWxworkInfoPageVo.setMobileMsgHandler(0);
                    }
                }

                //机器人分组
                if (deviceWxworkInfo.getGroupId() != null) {
                    DeviceGroup deviceGroup = deviceGroupMapper.selectById(deviceWxworkInfo.getGroupId(), deviceWxworkInfo.getMerId());
                    if (deviceGroup != null) {
                        deviceWxworkInfoPageVo.setGroupName(deviceGroup.getName());
                    }
                }

                //获取配置信息
                if (deviceWxworkInfo.getConfigId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
                    if (configPlan != null) {
                        deviceWxworkInfoPageVo.setConfigName(configPlan.getName());
                    }
                }

                //是否可以转移授权时间
                boolean transferAuthTimeFlag = false; //默认不可以

                //授权信息
                List<DeviceAuthVo> deviceAuthVoList = new ArrayList<>();
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
                //deviceAuthQuery.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if (deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        DeviceAuthVo deviceAuthVo = new DeviceAuthVo();
                        BeanUtils.copyProperties(deviceAuth, deviceAuthVo);
                        WxworkProductKeyEnum wxworkProductKeyEnum = WxworkProductKeyEnum.getValue(deviceAuth.getProductCode());
                        if (wxworkProductKeyEnum != null) {
                            deviceAuthVo.setProductName(wxworkProductKeyEnum.getDesc());
                        }
                        //到期时间
                        Integer expiretime = Tools.getInteger(deviceAuthVo.getExpireTime());
                        if (expiretime.intValue() <= now.intValue()) {
                            deviceAuthVo.setExpireStatus(0);  //已到期
                        } else if (expiretime.intValue() > now && expiretime.intValue() <= now + 7 * 24 * 3600) {
                            deviceAuthVo.setExpireStatus(2);  //即将到期
                        } else {
                            deviceAuthVo.setExpireStatus(1);  //未到期
                            transferAuthTimeFlag = true; //只要有未到期的授权产品，就可以转移授权时间
                        }
                        deviceAuthVoList.add(deviceAuthVo);
                    }
                }

                //封装授权记录
                deviceWxworkInfoPageVo.setDeviceAuthVoList(deviceAuthVoList);

                //设置是否可以转移授权时间
                if (transferAuthTimeFlag) {
                    deviceWxworkInfoPageVo.setTransferAuthTimeFlag(1);
                } else {
                    deviceWxworkInfoPageVo.setTransferAuthTimeFlag(0);
                }

                //封装报警规则信息
                if (deviceWxworkInfo.getAlarmRuleId() != null) {
                    AlarmRule alarmRule = alarmRuleMapper.selectById(deviceWxworkInfo.getAlarmRuleId(), deviceWxworkInfo.getMerId());
                    if (alarmRule != null) {
                        AlarmRuleInfoVo alarmRuleInfoVo = new AlarmRuleInfoVo();
                        BeanUtils.copyProperties(alarmRule, alarmRuleInfoVo);
                        deviceWxworkInfoPageVo.setAlarmRuleInfoVo(alarmRuleInfoVo);
                    }
                }

                //从缓存中换取企业微信信息
                deviceWxworkInfoPageVo.setPcDeviceAuthStatus(0);//未授权
                Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                if (object != null) {
                    DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object), DeviceInfoWxWorkCacheDto.class);
                    //企业微信缓存信息不为空
                    if (deviceInfoWxWorkCacheDto != null) {

                        //有pc端授权
                        deviceWxworkInfoPageVo.setPcDeviceAuthStatus(1);//有授权
                        //封装pc端授权
                        deviceWxworkInfoPageVo.setPcDeviceAuthVoList(deviceAuthVoList);

                        //PC端客户端版本号
                        deviceWxworkInfoPageVo.setPcClientVersion(deviceInfoWxWorkCacheDto.getClientVersion());
                        deviceWxworkInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.NO_UPDATE.getId());  //默认版本相同，不更新
                        //查询机器人最新版本
                        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                        if (deviceVersion != null) {
                            if (deviceVersion.getVersion() != null) {
                                //版本号不相等，有更新
                                if (!deviceVersion.getVersion().equals(deviceInfoWxWorkCacheDto.getClientVersion())) {
                                    deviceWxworkInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.HAVE_UPDATE.getId()); //版本号不相同，需要更新
                                    Integer updatePcClientVersionStatus = deviceInfoWxWorkCacheDto.getUpdateClientVersionStatus();
                                    Integer updatePcClientVersionTime = deviceInfoWxWorkCacheDto.getUpdateClientVersionTime();
                                    if (updatePcClientVersionStatus != null && updatePcClientVersionStatus == DeviceUpdateVersionStatusEnum.UPDATING.getId().intValue()) {//更新中
                                        deviceWxworkInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.UPDATING.getId());
                                        if (now - updatePcClientVersionTime > Const.Device.UPDATE_VERSION_VALIDITY_TIME) {//更新失败
                                            deviceWxworkInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.UPDATE_FAILE.getId());
                                        }
                                    }
                                }
                            }
                        }

                        //PC端微信版本号
                        deviceWxworkInfoPageVo.setPcWxVersion(deviceInfoWxWorkCacheDto.getWxVersion());
                        //是否在线，默认为离线
                        deviceWxworkInfoPageVo.setPcOnLine(0);
                        //获取最新心跳时间
                        Integer lastHeartBeatTime = deviceInfoWxWorkCacheDto.getLastHeartBeatTime();
                        if (lastHeartBeatTime != null) {
                            //判断在线（少于5分钟表示在线）
                            if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                deviceWxworkInfoPageVo.setPcOnLine(1); //在线
                            }
                        }

                        //操作系统版本
                        deviceWxworkInfoPageVo.setSysVersion(deviceInfoWxWorkCacheDto.getSysVersion());
                        //CPU使用率
                        deviceWxworkInfoPageVo.setSysCpuUse(deviceInfoWxWorkCacheDto.getSysCpuUse());
                        //内存使用率
                        deviceWxworkInfoPageVo.setSysMemUse(deviceInfoWxWorkCacheDto.getSysMemUse());
                        //磁盘总空间(MB)
                        deviceWxworkInfoPageVo.setDiskTotal(deviceInfoWxWorkCacheDto.getDiskTotal());
                        //硬盘可使用的空间(MB)
                        deviceWxworkInfoPageVo.setDiskFree(deviceInfoWxWorkCacheDto.getDiskFree());

                    }
                }

                try {
                    //从缓存中获取企业微信手机端信息
                    deviceWxworkInfoPageVo.setMobileDeviceAuthStatus(0);//无授权
                    Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                    if (object_mobile != null) {
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWxWorkCacheDto.class);
                        //手机端企业微信信息不为空
                        if (deviceInfoMobileWxWorkCacheDto != null) {

                            //有移动端授权
                            deviceWxworkInfoPageVo.setMobileDeviceAuthStatus(1);//有授权
                            //封装移动端授权
                            deviceWxworkInfoPageVo.setMobileDeviceAuthVoList(deviceAuthVoList);

                            //客户端版本号
                            deviceWxworkInfoPageVo.setMobileClientVersion(deviceInfoMobileWxWorkCacheDto.getClientVersion());
                            deviceWxworkInfoPageVo.setUpdateMobileClientVersion(0); //默认版本相同，不更新
                            //获取机器人最新移动端版本
                            //从缓存中获取版本移动端版本信息
                            Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.WXWORK_MOBILE_APP_UPDATE_INFO.getKey());
                            if (object_mobile_version != null) {
                                JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
                                if (jsonObject != null) {
                                    //软件版本号
                                    Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
                                    //软件版本名称
                                    String version = Tools.getStr(jsonObject.getString("version"));
                                    //包名称
                                    String packageName = Tools.getStr(jsonObject.getString("packageName"));
                                    //软件包URL地址
                                    String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));
                                    //版本号不相等，有更新
                                    if (!version.equals(deviceInfoMobileWxWorkCacheDto.getClientVersion())) {
                                        deviceWxworkInfoPageVo.setUpdateMobileClientVersion(1); //版本号不相同，需要更新
                                    }
                                }
                            }

                            //移动微信版本号
                            deviceWxworkInfoPageVo.setMobileWxVersion(deviceInfoMobileWxWorkCacheDto.getWxVersion());
                            //是否在线，默认为离线
                            deviceWxworkInfoPageVo.setMobileOnLine(0);
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoMobileWxWorkCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWxworkInfoPageVo.setMobileOnLine(1); //在线
                                }
                            }

                            //软件到期日期
                            //deviceWechatInfoPageVo.setMobileExpireTime(deviceInfoMobileWeChatCacheDto.getExpireTime());
                            //是否处理消息
                            //deviceWechatInfoPageVo.setMobileMsgHandler(deviceInfoMobileWeChatCacheDto.getMsgHandler());

                            //手机剩余电量百分比
                            deviceWxworkInfoPageVo.setBatteryLevel(Tools.getInteger(deviceInfoMobileWxWorkCacheDto.getBatteryLevel()));
                            //手机外部存储（sdcard）剩余空间字节数
                            Long sdCardFree = Tools.getLong(deviceInfoMobileWxWorkCacheDto.getSdCardFree());
                            deviceWxworkInfoPageVo.setSdCardFree(Math.round(sdCardFree / 1024d / 1024d, 2));
                        }
                    }
                } catch (Exception e) {

                }

                //最后登录ip地址
                try {
                    if (StringUtils.isNotBlank(deviceWxworkInfo.getLastLoginIp())) {
                        deviceWxworkInfoPageVo.setLastLoginIpAddress(Tools.findDeviceIpByRegex(deviceWxworkInfo.getLastLoginIp()));
                    }
                } catch (Exception e) {
                    logger.error("解析机器人最后登录ip地址错误，lastLoginIp={}, error={}", deviceWxworkInfo.getLastLoginIp(), e.getMessage());
                }


                deviceWxworkInfoPageVoList.add(deviceWxworkInfoPageVo);

                //刷新授权
                flashDeviceAuth(deviceWxworkInfo, deviceAuthList);

            }
        }

        //返回到页面分页对象
        Page<DeviceWxworkInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(deviceWxworkInfoPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询个人微信详情
     *
     * @param deviceWxworkInfoIdDto
     * @return DeviceWxworkInfoVo
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public DeviceWxworkInfoVo findDeviceWxworkInfoInfo(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信机器人不存在");
        }
        DeviceWxworkInfoVo deviceWxworkInfoPageVo = new DeviceWxworkInfoVo();

        BeanUtils.copyProperties(deviceWxworkInfo, deviceWxworkInfoPageVo);

        return deviceWxworkInfoPageVo;
    }

    /**
     * 修改机器人信息
     *
     * @param deviceWxworkInfoDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateDeviceWxworkInfo(DeviceWxworkInfoDto deviceWxworkInfoDto) {

        if (deviceWxworkInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        if (deviceWxworkInfoDto.getConfigId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoDto.getId(), deviceWxworkInfoDto.getMerId());
        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信不存在");
        }

        //判断是否修改了配置方案id,如果修改了配置方案id,则需要判断配置方案里会员类型组是否不一样，如果不一样，则不能修改
        if (deviceWxworkInfoDto.getConfigId().longValue() != Tools.getLong(deviceWxworkInfo.getConfigId())) {
            ConfigPlan configPlanOld = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
            ConfigPlan configPlanNew = configPlanMapper.selectById(deviceWxworkInfoDto.getConfigId(), deviceWxworkInfoDto.getMerId());
            if (configPlanOld != null && configPlanNew != null) {
                if (Tools.getLong(configPlanOld.getUserTypeGroupId()).longValue() != Tools.getLong(configPlanNew.getUserTypeGroupId()).longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新修改的配置方案里的会员类型组和旧配置方案里会员类型组不一样");
                }
            }
        }

        Integer now = DateUtil.getNowTime();
        deviceWxworkInfo.setDeviceName(deviceWxworkInfoDto.getDeviceName());
        deviceWxworkInfo.setDeviceRemark(deviceWxworkInfoDto.getDeviceRemark());
        deviceWxworkInfo.setGroupId(deviceWxworkInfoDto.getGroupId());
        deviceWxworkInfo.setConfigId(deviceWxworkInfoDto.getConfigId());
        deviceWxworkInfo.setAutoReplace(Tools.getInteger(deviceWxworkInfoDto.getAutoReplace()));
        deviceWxworkInfo.setConfigRule(deviceWxworkInfoDto.getConfigRule());
        deviceWxworkInfo.setUpdateTime(now);
        deviceWxworkInfoMapper.updateById(deviceWxworkInfo);

        //更新redis
        Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        if (object != null) {
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            jsonObject.put("configId", deviceWxworkInfo.getConfigId());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), jsonObject.toJSONString());
        }
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        if (object_mobile != null) {
            JSONObject jsonObject = JSONObject.parseObject(object_mobile.toString());
            jsonObject.put("configId", deviceWxworkInfo.getConfigId());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), jsonObject.toJSONString());
        }

        //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
        ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfoDto.getMerId());
        if (configPlan != null && configPlan.getOtherId() != null) {
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWxworkInfoDto.getMerId());
            if (sysPlugin != null) {
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWxworkInfo.getId()), sysPlugin.getData());
            }
        }
    }

    /**
     * 批量修改企业机器人信息
     *
     * @param deviceWxworkInfoBatchDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void batchUpdateDeviceWxworkInfo(DeviceWxworkInfoBatchDto deviceWxworkInfoBatchDto) {
        if (deviceWxworkInfoBatchDto.getIdList() == null || deviceWxworkInfoBatchDto.getIdList().size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        Long configId = deviceWxworkInfoBatchDto.getConfigId();
        ConfigPlan configPlan = null;
        if (configId != null) {
            configPlan = configPlanMapper.selectById(configId, deviceWxworkInfoBatchDto.getMerId());
            if (configPlan == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
            }
        }

        Long groupId = deviceWxworkInfoBatchDto.getGroupId();
        if (groupId != null) {
            DeviceGroup deviceGroup = deviceGroupMapper.selectById(groupId, deviceWxworkInfoBatchDto.getMerId());
            if (deviceGroup == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人分组不存在");
            }
        }

        //配置方案启用规则
        Integer configRule = deviceWxworkInfoBatchDto.getConfigRule();

        for (Long id : deviceWxworkInfoBatchDto.getIdList()) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoBatchDto.getMerId());
            if (deviceWxworkInfo == null) {
                continue;
            }

            //判断是否修改了配置方案id,如果修改了配置方案id,则需要判断配置方案里会员类型组是否不一样，如果不一样，则不能修改
            if (Tools.getLong(deviceWxworkInfoBatchDto.getConfigId()).longValue() != Tools.getLong(deviceWxworkInfo.getConfigId())) {
                ConfigPlan configPlanOld = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
                ConfigPlan configPlanNew = configPlanMapper.selectById(deviceWxworkInfoBatchDto.getConfigId(), deviceWxworkInfoBatchDto.getMerId());
                if (configPlanOld != null && configPlanNew != null) {
                    if (Tools.getLong(configPlanOld.getUserTypeGroupId()).longValue() != Tools.getLong(configPlanNew.getUserTypeGroupId()).longValue()) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人id:" + deviceWxworkInfo.getId() + "新修改的配置方案里的会员类型组和旧配置方案里会员类型组不一样");
                    }
                }
            }

            Integer now = DateUtil.getNowTime();

            if (configId != null) {
                deviceWxworkInfo.setConfigId(configId);
            }

            if (groupId != null) {
                deviceWxworkInfo.setGroupId(groupId);
            }

            if (configRule != null) {
                deviceWxworkInfo.setConfigRule(configRule);
            }

            deviceWxworkInfo.setUpdateTime(now);
            deviceWxworkInfo.setAutoReplace(Tools.getInteger(deviceWxworkInfoBatchDto.getAutoReplace()));
            deviceWxworkInfoMapper.updateById(deviceWxworkInfo);

            //更新redis
            if (configId != null) {
                Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), id));
                if (object != null) {
                    JSONObject jsonObject = JSONObject.parseObject(object.toString());
                    jsonObject.put("configId", configId);
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), id), jsonObject.toJSONString());
                }

                Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                if (object_mobile != null) {
                    JSONObject jsonObject = JSONObject.parseObject(object_mobile.toString());
                    jsonObject.put("configId", deviceWxworkInfo.getConfigId());
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), jsonObject.toJSONString());
                }

                //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                if (configPlan != null && configPlan.getOtherId() != null) {
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWxworkInfo.getMerId());
                    if (sysPlugin != null) {
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWxworkInfo.getId()), sysPlugin.getData());
                    }
                }
            }
        }
    }

    /**
     * 个人微信机器人删除
     *
     * @param deviceWxworkInfoDelDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Boolean delDeviceWxworkInfo(DeviceWxworkInfoDelDto deviceWxworkInfoDelDto) {

        int now = DateUtil.getNowTime();
        Long merId = deviceWxworkInfoDelDto.getMerId();

        Long id = deviceWxworkInfoDelDto.getId();
        Long transferId = deviceWxworkInfoDelDto.getTransferId();

        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoDelDto.getId(), deviceWxworkInfoDelDto.getMerId());
        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //需要转移机器人，则必须要选择转移的新机器人
        if (transferId != null) {
            if (id.longValue() == transferId.longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
            }
            DeviceWxworkInfo deviceWxworkInfo_transfer = deviceWxworkInfoMapper.selectById(transferId, deviceWxworkInfoDelDto.getMerId());
            if (deviceWxworkInfo_transfer == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不存在");
            }

            ConfigPlan configPlan_self = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
            if (configPlan_self == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移的机器人配置方案不存在");
            }

            ConfigPlan configPlan_transfer = configPlanMapper.selectById(deviceWxworkInfo_transfer.getConfigId(), deviceWxworkInfo_transfer.getMerId());
            if (configPlan_transfer == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人配置方案不存在");
            }

            if (Tools.getLong(configPlan_self.getUserTypeGroupId()).longValue() != Tools.getLong(configPlan_transfer.getUserTypeGroupId()).longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人的会员类型组与旧的不一样");
            }

            //转移会员
            wxworkUserMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
        }

        deviceWxworkInfoMapper.deleteById(deviceWxworkInfoDelDto.getId(), deviceWxworkInfoDelDto.getMerId());

        //删除该机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWxworkInfo.getDeviceId());

        //清除机器人所有运营商缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWxworkInfo.getDeviceId()));
        //删除企业微信机器人缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        //删除企业微信通讯录
        wxworkContactsService.deleteWxContactsByDeviceUniqueId(deviceWxworkInfo.getId(), deviceWxworkInfo.getMerId());
        //删除企业微信群
        wxWorkGroupService.deleteWxWorkGroupByDeviceUniqueId(deviceWxworkInfo.getId(), deviceWxworkInfo.getMerId());

        //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
        ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
        if (configPlan != null && configPlan.getOtherId() != null) {
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWxworkInfo.getMerId());
            if (sysPlugin != null) {
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWxworkInfo.getId()));
            }
        }
        return true;
    }

    /**
     * 企业微信机器人批量删除
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Boolean batchDelDeviceWxworkInfo(@RequestBody DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {
        //主键idList
        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }
        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());
            if (deviceWxworkInfo != null) {
                deviceWxworkInfoMapper.deleteById(id, deviceWxworkInfoIdListDto.getMerId());

                //删除该机器人的授权
                deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWxworkInfo.getDeviceId());

                //清除机器人所有运营商缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWxworkInfo.getDeviceId()));
                //删除企业微信机器人缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                //删除企业微信通讯录
                wxworkContactsService.deleteWxContactsByDeviceUniqueId(deviceWxworkInfo.getId(), deviceWxworkInfo.getMerId());
                //删除企业微信群
                wxWorkGroupService.deleteWxWorkGroupByDeviceUniqueId(deviceWxworkInfo.getId(), deviceWxworkInfo.getMerId());

                //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                ConfigPlan configPlan = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
                if (configPlan != null && configPlan.getOtherId() != null) {
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWxworkInfo.getMerId());
                    if (sysPlugin != null) {
                        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWxworkInfo.getId()));
                    }
                }
            }
        }
        return true;
    }

    /**
     * 更新电脑端客户端软件
     *
     * @param deviceWxworkInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updatePcClientSoft(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //从缓存中换取企业微信信息
        Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object), DeviceInfoWxWorkCacheDto.class);

        //企业微信信息不为空
        if (deviceInfoWxWorkCacheDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人还未曾登录过，不能更新版本");
        }

        //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
        Integer updateClientVersionStatus = deviceInfoWxWorkCacheDto.getUpdateClientVersionStatus();
        Integer updateClientVersionTime = deviceInfoWxWorkCacheDto.getUpdateClientVersionTime();
        if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
            if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人版本正在更新中 ，请稍后再试");
            }
        }

        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
        if (deviceVersion == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人最新版本为空");
        }

        //发送MQ消息
        MsgDto<UpdateClientAppDto> msgDto = new MsgDto<>();
        UpdateClientAppDto updateClientAppDto = new UpdateClientAppDto();
        msgDto.setContent(updateClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.UPDATE_CLIENT.getValue());
        updateClientAppDto.setUpdateType(1); //常规更新
        updateClientAppDto.setIsRunApp(1);   //启动
        updateClientAppDto.setNewVersion(deviceVersion.getVersion());
        noticeMsgPushProducerService.updateClientApp(msgDto);

        //修改Redis状态
        deviceInfoWxWorkCacheDto.setUpdateClientVersionStatus(2);
        deviceInfoWxWorkCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
    }

    /**
     * 批量更新电脑端客户端软件
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchUpdatePcClientSoft(DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {

        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());
            if (deviceWxworkInfo == null) {
                continue;
            }

            //从缓存中换取企业微信信息
            Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object), DeviceInfoWxWorkCacheDto.class);

            //企业微信信息不为空
            if (deviceInfoWxWorkCacheDto == null) {
                continue;
            }

            //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
            Integer updateClientVersionStatus = deviceInfoWxWorkCacheDto.getUpdateClientVersionStatus();
            Integer updateClientVersionTime = deviceInfoWxWorkCacheDto.getUpdateClientVersionTime();
            if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
                if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                    continue;
                }
            }

            DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
            if (deviceVersion == null) {
                continue;
            }


            //发送MQ消息
            MsgDto<UpdateClientAppDto> msgDto = new MsgDto<>();
            UpdateClientAppDto updateClientAppDto = new UpdateClientAppDto();
            msgDto.setContent(updateClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            msgDto.setMerId(deviceWxworkInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.UPDATE_CLIENT.getValue());
            updateClientAppDto.setUpdateType(1); //强制更新
            updateClientAppDto.setIsRunApp(1);   //启动
            updateClientAppDto.setNewVersion(deviceVersion.getVersion());
            noticeMsgPushProducerService.updateClientApp(msgDto);

            //修改Redis状态
            deviceInfoWxWorkCacheDto.setUpdateClientVersionStatus(2);
            deviceInfoWxWorkCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
        }
    }

    /**
     * 重启电脑端客户端软件
     *
     * @param deviceWxworkInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void restartPcClientSoft(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(2); //重启客户端软件
        noticeMsgPushProducerService.closeClientApp(msgDto);

    }

    /**
     * 批量重启电脑端客户端软件
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchRestartPcClientSoft(DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {
        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());
            if (deviceWxworkInfo == null) {
                continue;
            }
            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            msgDto.setMerId(deviceWxworkInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(2); //重启客户端软件
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 退出电脑端客户端软件
     *
     * @param deviceWxworkInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void quitPcClientSoft(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(4); //退出客户端软件
        noticeMsgPushProducerService.closeClientApp(msgDto);
    }

    /**
     * 批量退出电脑端客户端软件
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchQuitPcClientSoft(DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {
        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());
            if (deviceWxworkInfo == null) {
                continue;
            }
            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            msgDto.setMerId(deviceWxworkInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(4); //退出客户端软件
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 退出电脑端微信
     *
     * @param deviceWxworkInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void quitPcWechat(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(5); //退出电脑端微信
        noticeMsgPushProducerService.closeClientApp(msgDto);
    }

    /**
     * 批量退出电脑端微信
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchQuitPcWechat(DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {
        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());

            if (deviceWxworkInfo == null) {
                continue;
            }

            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            msgDto.setMerId(deviceWxworkInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(5); //退出电脑端微信
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 购买授权
     *
     * @param deviceWxworkInfoBuyAuthDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public DeviceWxworkInfoAddVo buyDeviceAuth(DeviceWxworkInfoBuyAuthDto deviceWxworkInfoBuyAuthDto) {

        //判断是否已经实名验证
        RealNameVerificationJson realNameVerificationJson = merchantService.getRealNameInfo(deviceWxworkInfoBuyAuthDto.getMerId());
        if (realNameVerificationJson == null || StringUtils.isBlank(realNameVerificationJson.getIdCard())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "需要验证运营商是否实名，未实名需要到【账号设置】中设置实名信息");
        }

        DeviceWxworkInfoAddVo deviceWechatInfoAddVo = new DeviceWxworkInfoAddVo();
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        Integer now = DateUtil.getNowTime();
        Long merId = deviceWxworkInfoBuyAuthDto.getMerId();

        //取出机器人列表
        List<Long> idList = deviceWxworkInfoBuyAuthDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备id");
        }

        //支付类型
        Integer payType = deviceWxworkInfoBuyAuthDto.getPayType();
        if (payType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付类型");
        }

        //购买产品
        String productCode_auth = deviceWxworkInfoBuyAuthDto.getProductCode();
        if (StringUtils.isBlank(productCode_auth)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择授权产品");
        }
        DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
        if (deviceProduct_auth == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置该设备产品功能");
        }

        //从枚举中获取关联的产品
        WxworkDeviceProductEnum wxworkDeviceProductEnum = WxworkDeviceProductEnum.getValue(deviceProduct_auth.getCode());
        List<String> productCodeList = JSONObject.parseArray(wxworkDeviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还没配置该设备产品功能");
        }

        //判断支付类型
        if (payType.intValue() == PaymentTypeEnum.PAY_BALANCE.getId().intValue()) {//余额支付

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceWxworkInfoBuyAuthDto.getAuthType();
            if (authType == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
            }

            //授权数量
            Integer quantity = deviceWxworkInfoBuyAuthDto.getQuantity();
            if (quantity == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
            }

            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
                if (quantity.intValue() > 120) { //不能超过120月
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
                }
            } else { //按年购买
                if (quantity.intValue() > 10) { //不能超过10年
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
                }
            }

            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;

            //总金额
            DeviceWxworkAmountDto deviceWxworkAmountDto = new DeviceWxworkAmountDto();
            BeanUtils.copyProperties(deviceWxworkInfoBuyAuthDto, deviceWxworkAmountDto);
            deviceWxworkAmountDto.setIdList(idList);
            DeviceAmountVo deviceAmountVo = getAmount(deviceWxworkAmountDto);
            Double amountTotal = Tools.getDouble(deviceAmountVo.getAmountTotal());

            if (amountTotal.doubleValue() <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择授权时长已经存在");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
            if (devicePrice_buy == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for (String productCode : productCodeList) {
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //新的到期时间
            Integer expired_time = 0;

            //保存账户余额
            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(merId);
            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }

            //判断余额大小
            Double balance = merchant.getBalance();
            if (balance.doubleValue() < amountTotal.doubleValue()) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance - amountTotal);
            merchant.setUpdateTime(now);
            merchantMapper.updateBalance(merchant);

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(amountTotal);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.WXWORK_AUTH.getId());
            merAccDetail.setSubtype(productCode_auth);
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //循环批量操作的机器人
            for (Long deviceUniqueId : idList) {

                //查询机器人信息
                DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, deviceWxworkInfoBuyAuthDto.getMerId());
                if (deviceWxworkInfo == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的企业微信机器人不存在");
                }
                String deviceId = deviceWxworkInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                } else {//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if (productCodeList.size() == 1) { //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);
                    //查询产品价格
                    DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                    if (devicePrice == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置机器人该端的购买价格");
                    }

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    if (deviceAuth != null) {//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if (old_expireTime <= now) {//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        } else {
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    } else {
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceAuth.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                        deviceAuth.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(deviceWxworkInfoBuyAuthDto.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                    deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(deviceWxworkInfoBuyAuthDto.getAuthType());
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(deviceWxworkInfoBuyAuthDto.getPayType());
                    deviceAuthDetail.setTradeno(trandeNo);
                    deviceAuthDetail.setAmount(amountTotal);
                    deviceAuthDetail.setRemark("余额支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);

                } else { //全包产品

                    for (String productCode : productCodeList) {

                        //查询产品价格
                        DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                        if (devicePrice == null) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器该端的购买价格");
                        }

                        //产品单价
                        Double product_price = Tools.getDouble(devicePrice.getPrice());
                        //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                        Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));

                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                        //还未授权
                        if (deviceAuth == null) {
                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(merId);
                            deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                            deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                            deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                            deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                            deviceAuthDetail.setTradeno(trandeNo);
                            deviceAuthDetail.setRemark("余额支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(amountTotal);
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
                            deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
                            deviceAuth.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                            deviceAuth.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(merId);
                                deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                                deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                                deviceAuthDetail.setTradeno(trandeNo);
                                deviceAuthDetail.setRemark("余额支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(amountTotal);
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if (old_expireTime > now && old_expireTime < expired_time) {

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(merId);
                                deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                                deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                                deviceAuthDetail.setTradeno(trandeNo);
                                deviceAuthDetail.setRemark("余额支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(amountTotal);
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if (deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    //更新redis
                    Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                    if (object_pc != null) { //修改
                        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoWxWorkCacheDto.class);
                        if (deviceInfoWxWorkCacheDto != null) {
                            deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                            //更新企业微信机器人redis
                            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
                        }
                    } else {//新增
                        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = new DeviceInfoWxWorkCacheDto();
                        deviceInfoWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
                        deviceInfoWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceInfoWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                        deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        deviceInfoWxWorkCacheDto.setMsgHandler(DeviceTypeEnum.DT_WORK_WECHAT_VALUE); //接收消息
                        if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId()) { //PC端接收消息
                            deviceInfoWxWorkCacheDto.setMsgHandler(1); //接收消息
                        } else {
                            deviceInfoWxWorkCacheDto.setMsgHandler(0); //不接受消息
                        }
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
                    }

                    //更新移动端redis
                    Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                    if (object_moblie != null) { //修改
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWxWorkCacheDto.class);
                        if (deviceInfoMobileWxWorkCacheDto != null) {
                            deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));

                    } else {
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = new DeviceInfoMobileWxWorkCacheDto();
                        deviceInfoMobileWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                        deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                        deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                        if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()) { //手机端接收消息
                            deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
                        } else {
                            deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
                    }

                }
                //异步执行给机器人移动端APP授权
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceId, deviceWxworkInfo.getRecvmsgType());
            }
        } else if (payType.intValue() == PaymentTypeEnum.PAY_ALIPAY.getId().intValue()) { //支付宝支付
            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceWxworkInfoBuyAuthDto.getAuthType();
            if (authType == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
            }

            //授权数量
            Integer quantity = deviceWxworkInfoBuyAuthDto.getQuantity();
            if (quantity == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
            }

            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
                if (quantity.intValue() > 120) { //不能超过120月
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
                }
            } else { //按年购买
                if (quantity.intValue() > 10) { //不能超过10年
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
                }
            }

            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;

            //总金额
            DeviceWxworkAmountDto deviceWxworkAmountDto = new DeviceWxworkAmountDto();
            BeanUtils.copyProperties(deviceWxworkInfoBuyAuthDto, deviceWxworkAmountDto);
            deviceWxworkAmountDto.setIdList(idList);
            DeviceAmountVo deviceAmountVo = getAmount(deviceWxworkAmountDto);
            Double amountTotal = Tools.getDouble(deviceAmountVo.getAmountTotal());

            if (amountTotal.doubleValue() <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择授权时长已经存在");
            }

            //新的到期时间
            Integer expired_time = 0;

            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(deviceWxworkInfoBuyAuthDto.getMerId());
            alipayDetail.setTradeno(trandeNo);
            alipayDetail.setType(AlipayTypeEnum.DEVICE_WXWORK_AUTH.getId()); //续费企业微信
            alipayDetail.setSubtype(productCode_auth);

            //业务信息
            DeviceAuthBusinessInfo deviceAuthBusinessInfo = new DeviceAuthBusinessInfo();
            deviceAuthBusinessInfo.setDeviceUniqueIdList(deviceWxworkInfoBuyAuthDto.getIdList());
            deviceAuthBusinessInfo.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            deviceAuthBusinessInfo.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
            deviceAuthBusinessInfo.setAuthType(deviceWxworkInfoBuyAuthDto.getAuthType());
            deviceAuthBusinessInfo.setQuantity(quantity);
            deviceAuthBusinessInfo.setAmount(amountTotal);
            deviceAuthBusinessInfo.setProductCode(productCode_auth);

            //查询产品价格
            DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
            if (devicePrice == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器该端的购买价格");
            }
            deviceAuthBusinessInfo.setPrice(devicePrice.getPrice());
            alipayDetail.setBusinessInfo(Tools.getStrEmpty(JSONObject.toJSONString(deviceAuthBusinessInfo)));

            alipayDetail.setAmount(amountTotal);
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            alipayDetailCreateDto.setSubject(AlipayTypeEnum.DEVICE_WXWORK_AUTH.getDesc());

            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if (StringUtils.isNotBlank(alipayUrl)) {
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);
                //返回支付页面
                deviceWechatInfoAddVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl() + "?id=" + alipayDetail.getId());
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        } else if (payType.intValue() == PaymentTypeEnum.PAY_CARDID.getId().intValue()) { //卡密支付
            //返回每个设备对于卡密的充值结果信息
            List<CardBuyResult> cardBuyResultList = new ArrayList<>();
            deviceWechatInfoAddVo.setCardBuyResultList(cardBuyResultList);
            //取出卡密列表
            List<String> cardList = deviceWxworkInfoBuyAuthDto.getCardList();
            if (cardList == null || cardList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入卡密");
            }

            //循环设备id列表
            for (int i = 0; i < idList.size(); i++) {
                //卡密购买返回结果
                CardBuyResult cardBuyResult = new CardBuyResult();
                cardBuyResult.setMsg("购买失败");
                //先封装近返回list
                cardBuyResultList.add(cardBuyResult);

                try { //每个设备单独提交
                    Long deviceUniqueId = idList.get(i);
                    DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, merId);
                    if (deviceWxworkInfo != null) {
                        cardBuyResult.setDeviceName(deviceWxworkInfo.getDeviceName()); //返回设备昵称
                        if (i < cardList.size()) {
                            //取出对于下标的卡密
                            String card = cardList.get(i);
                            cardBuyResult.setCard(card);  //返回卡密信息
                            //查询该卡信息
                            Cdkeys cdkeys = cdkeysMapper.selectByCard(card);

                            if (cdkeys == null) {
                                cardBuyResult.setMsg("卡密错误");
                                continue;
                            }

                            if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.ALL.getId().intValue()) {
                                if (!productCode_auth.equals(WxworkDeviceProductEnum.ALL.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 企业微信 全部功能 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.FL.getId().intValue()) {
                                if (!productCode_auth.equals(WxworkDeviceProductEnum.FL.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 企业微信 返利 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.UZAICHAT.getId().intValue()) {
                                if (!productCode_auth.equals(WxworkDeviceProductEnum.UZAICHAT.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 企业微信 悠聊 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.FD.getId().intValue()) {
                                if (!productCode_auth.equals(WxworkDeviceProductEnum.FD.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 企业微信 社群群发 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.TUO.getId().intValue()) {
                                if (!productCode_auth.equals(WxworkDeviceProductEnum.TUO.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 企业微信 气氛组 卡");
                                    continue;
                                }
                            }
//
//                            if(productCode_auth.equals(WxworkDeviceProductEnum.ALL.getValue())){ //全部产品
//                                if(cdkeys.getProductType().intValue() != CdkeysProductTypeEnum.ALL.getId()){ //必须是全部产品功能卡
//                                    cardBuyResult.setMsg("卡密类型错误");
//                                    continue;
//                                }
//                            }else if(productCode_auth.equals(WxworkDeviceProductEnum.FL.getValue())){//返利
//                                if(cdkeys.getProductType().intValue() != CdkeysProductTypeEnum.FL.getId()){ //返利功能卡
//                                    cardBuyResult.setMsg("卡密类型错误");
//                                    continue;
//                                }
//                            }else if(productCode_auth.equals(WxworkDeviceProductEnum.UZAICHAT.getValue())){
//                                if(cdkeys.getProductType().intValue() != CdkeysProductTypeEnum.UZAICHAT.getId()){ //悠聊功能卡
//                                    cardBuyResult.setMsg("卡密类型错误");
//                                    continue;
//                                }
//                            }

                            if (Tools.getInteger(cdkeys.getDeviceTypeId()).intValue() != DeviceTypeEnum.DT_WORK_WECHAT.getId()) {//企业微信
                                cardBuyResult.setMsg("不是企业微信卡密");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.USED.getId().intValue()) {//卡密已使用
                                cardBuyResult.setMsg("卡密已使用");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.INVALID.getId().intValue()) {//卡密已作废
                                cardBuyResult.setMsg("卡密已作废");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.STOCK.getId().intValue()) {//卡密还未出库
                                cardBuyResult.setMsg("卡密还未出库");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.OUTSTOCK.getId().intValue()) {//出库状态
                                deviceWechatInfoCardPayService.buyWxworkDeviceAuthByCard(deviceWxworkInfo, DeviceTypeEnum.DT_WORK_WECHAT.getId(), cdkeys, now, trandeNo, productCodeList);
                                cardBuyResult.setMsg("购买成功");
                            }
                        }
                    } else {
                        cardBuyResult.setMsg("机器人不存在");
                        continue;
                    }
                } catch (Exception e) {
                    logger.error("----机器人授权购买失败----error={}", e.getMessage());
                    cardBuyResult.setMsg("购买失败");
                }
            }
        }
        return deviceWechatInfoAddVo;
    }


    /**
     * 查询添加或者购买总金额
     *
     * @param deviceWxworkAmountDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public DeviceAmountVo getAmount(DeviceWxworkAmountDto deviceWxworkAmountDto) {

        //类型类型id
        Integer deviceTypeId = DeviceTypeEnum.DT_WORK_WECHAT_VALUE;
        if (deviceTypeId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型id");
        }

        //授权类型(1月卡;2年卡)
        Integer authType = deviceWxworkAmountDto.getAuthType();
        if (authType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
        }

        //购买数量
        Integer quantity = deviceWxworkAmountDto.getQuantity();
        if (quantity == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
        }

        if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
            if (quantity.intValue() > 120) { //不能超过120月
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
            }
        } else { //按年购买
            if (quantity.intValue() > 10) { //不能超过10年
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
            }
        }

        //返回对象
        DeviceAmountVo deviceAmountVo = new DeviceAmountVo();
        //封装机器人授权信息
        List<DeviceAmountVo.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();

        //设备id
        List<Long> idList = deviceWxworkAmountDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择需要购买授权的机器人");
        }

        //购买产品
        String productCode_buy = deviceWxworkAmountDto.getProductCode();
        if (StringUtils.isBlank(productCode_buy)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择购买产品功能");
        }
        DeviceProduct deviceProduct_buy = deviceProductMapper.selectByCode(productCode_buy);
        if (deviceProduct_buy == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置该产品功能");
        }
        //List<String> productCodeList_buy = JSONObject.parseArray(deviceProduct_buy.getCodes(), String.class);
        //从枚举中获取关联的产品
        WxworkDeviceProductEnum wxworkDeviceProductEnum = WxworkDeviceProductEnum.getValue(deviceProduct_buy.getCode());
        List<String> productCodeList_buy = JSONObject.parseArray(wxworkDeviceProductEnum.getCodes(), String.class);
        if (productCodeList_buy == null || productCodeList_buy.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还没配置该产品功能信息");
        }

        //查询产品的总价格
        DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_buy, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
        if (devicePrice_buy == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
        }
        //all产品
        Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
        //分别查询该产品包含的产品的总价格
        Double price_total = 0.00D;
        for (String productCode : productCodeList_buy) {
            //查询产品价格
            DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
            if (devicePrice == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
            }
            price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
        }
        //总单价的优惠
        Double price_discount = Math.sub(price_total, price_all);

        if (price_discount.doubleValue() < 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统产品价格设置错误");
        }

        //当天时间
        Integer now = DateUtil.getNowTime();
        //总金额
        Double amount_totle = 0.00D;
        //新的到期时间
        Integer expired_time = 0;
        //保存到数据库当中的购买月数，按年买需要乘以12月
        Integer quantity_db = 0;
        //循环批量操作的机器人
        for (Long deviceUniqueId : idList) {

            //查询机器人信息
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceUniqueId, deviceWxworkAmountDto.getMerId());
            if (deviceWxworkInfo == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的企业微信机器人不存在");
            }
            String deviceId = deviceWxworkInfo.getDeviceId();

            //本次授权开始时间默认为现在
            Integer begin_time = now;

            //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
            begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList_buy, now);

            //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                //新的到期时间=现在+月数*30天*24小时*3600秒
                expired_time = begin_time + quantity * 30 * 24 * 3600;
                quantity_db = quantity;
            } else {//按年购买
                //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                quantity_db = quantity * 12;
            }

            //判断购买的产品类型（全包类型需要补差价）
            if (productCodeList_buy.size() == 1) { //单个基础包，则需重新设置到期时间，直接时间累加
                //单个产品授权开始时间
                Integer beginTime_one = 0;
                //单个产品授权结束时间
                Integer expireTime_one = 0;
                //单个产品授权天数
                Integer authDays_one = quantity_db * 30;
                String productCode = productCodeList_buy.get(0);

                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置机器人该端的购买价格");
                }
                //单个机器人总金额=单价*购买时间数
                Double amount = Math.mul(Tools.getDouble(devicePrice.getPrice()), quantity);
                //总金额累加
                amount_totle = Math.add(amount_totle, amount);

                //计算产品授权记录
                //添加机器人授权表-如果没有则新增，有则修改
                DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                if (deviceAuth != null) {//修改
                    //判断旧到期时间是否已经过期
                    Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                    if (old_expireTime <= now) {//已经到期，则从今天开始算
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                    } else {
                        beginTime_one = old_expireTime;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                    }
                } else {
                    beginTime_one = now;
                    expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                }

                //机器人redis缓存信息-产品授权
                DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                deviceProductAuth.setAuthDays(authDays_one);
                deviceProductAuth.setExpireTime(expireTime_one);
                deviceProductAuth.setProductCode(productCode);
                deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                deviceProductAuthList.add(deviceProductAuth);

            } else { //全包产品

                //单个机器人总金额=单价*购买时间数
                Double amount = Math.mul(Tools.getDouble(devicePrice_buy.getPrice()), quantity);

                for (String productCode : productCodeList_buy) {

                    //单个产品授权天数
                    Integer authDays_one = quantity_db * 30;

                    //查询产品价格
                    DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_WORK_WECHAT_VALUE);
                    if (devicePrice == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器该端的购买价格");
                    }

                    //产品单价
                    Double product_price = devicePrice.getPrice();
                    //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                    Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));

                    //查询旧授权
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    //还未授权，不需要补差价
                    if (deviceAuth == null) {
                        //机器人redis缓存信息-产品授权
                        DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                        deviceProductAuth.setAuthDays(authDays_one);
                        deviceProductAuth.setExpireTime(expired_time);
                        deviceProductAuth.setProductCode(productCode);
                        deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                        deviceProductAuthList.add(deviceProductAuth);
                    } else { //授权存在，需判断授权的结束时间
                        //旧到期时间
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        //判断旧授权是否已经过期，
                        if (old_expireTime <= now) { //已经过期,也不需要补差价
                            //机器人redis缓存信息-产品授权
                            DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                            deviceProductAuth.setAuthDays(authDays_one);
                            deviceProductAuth.setExpireTime(expired_time);
                            deviceProductAuth.setProductCode(productCode);
                            deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                            deviceProductAuthList.add(deviceProductAuth);
                        } else if (old_expireTime > now && old_expireTime < expired_time) {
                            //需要补差价
                            Double differenceAmount = 0.00D;
                            //减去当前的时间，除以3600秒，再除以24小时取整，即是相差的天数
                            Double days = Math.div((old_expireTime - begin_time), 3600 * 24, 2);
                            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                                differenceAmount = Math.mul(Math.div(product_price_discount, 30), days, 2);
                            } else {//按年购买的
                                differenceAmount = Math.mul(Math.div(product_price_discount, 360), days, 2);
                            }
                            //单产品支付的金额
                            amount = Math.sub(amount, differenceAmount);

                            //授权的天数
                            authDays_one = authDays_one - days.intValue();

                            //机器人redis缓存信息-产品授权
                            DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                            deviceProductAuth.setAuthDays(authDays_one);
                            deviceProductAuth.setExpireTime(expired_time);
                            deviceProductAuth.setProductCode(productCode);
                            deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                            deviceProductAuthList.add(deviceProductAuth);

                        } else {
                            //需要补差价
                            Double differenceAmount = 0.00D;
                            //全额退款
                            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                                differenceAmount = Math.mul(Math.div(product_price_discount, 30), authDays_one, 2);
                            } else {
                                differenceAmount = Math.mul(Math.div(product_price_discount, 360), authDays_one, 2);
                            }
                            //单产品支付的金额
                            amount = Math.sub(amount, differenceAmount);
                        }
                    }
                }

                //总金额累加
                amount_totle = Math.add(amount_totle, amount);
            }
        }
        deviceAmountVo.setAmountTotal(amount_totle);
        deviceAmountVo.setDeviceProductAuthList(deviceProductAuthList);
        return deviceAmountVo;
    }

    /**
     * 刷新在线状态
     *
     * @param merId
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void refreshOnlineStatus(Long merId) {
        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先登录");
        }
        DeviceWxworkInfoQuery deviceWxworkInfoQuery = new DeviceWxworkInfoQuery();
        deviceWxworkInfoQuery.setMerId(merId);
        List<DeviceWxworkInfo> deviceWxworkInfoList = deviceWxworkInfoMapper.findByList(deviceWxworkInfoQuery);
        if (deviceWxworkInfoList != null && deviceWxworkInfoList.size() > 0) {

            for (DeviceWxworkInfo deviceWxworkInfo : deviceWxworkInfoList) {
                try {

                    //PC端
                    deviceWxworkInfo.setPcStatus(0); //默认离线
                    //从缓存中换取企业微信信息
                    Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
                    if (object != null) {
                        DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object), DeviceInfoWxWorkCacheDto.class);
                        //企业微信缓存信息不为空
                        if (deviceInfoWxWorkCacheDto != null) {
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoWxWorkCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWxworkInfo.setPcStatus(1); //在线
                                }
                            }
                        }
                    }

                    //移动端
                    deviceWxworkInfo.setMobileStatus(0); //默认离线
                    Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
                    if (object_mobile != null) {
                        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWxWorkCacheDto.class);
                        //手机端个人微信信息不为空
                        if (deviceInfoMobileWxWorkCacheDto != null) {
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoMobileWxWorkCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWxworkInfo.setMobileStatus(1); //在线
                                }
                            }
                        }
                    }

                    deviceWxworkInfoMapper.updateOnlineStatus(deviceWxworkInfo);

                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 增加试用期授权
     *
     * @param deviceWxworkInfoAddProbationAuth
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void addProbationAuth(@RequestBody DeviceWxworkInfoAddProbationAuth deviceWxworkInfoAddProbationAuth) {
        Long merId = deviceWxworkInfoAddProbationAuth.getMerId();

        if (merId == null
                || deviceWxworkInfoAddProbationAuth.getId() == null
                || StringUtils.isBlank(deviceWxworkInfoAddProbationAuth.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "参数不能为空");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoAddProbationAuth.getId(), deviceWxworkInfoAddProbationAuth.getMerId());
        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人唯一id不存在");
        }

        if (WxworkDeviceProductEnum.ALL.getValue().equals(deviceWxworkInfoAddProbationAuth.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前还未支持增加此产品试用期授权");
        }

        WxworkDeviceProductEnum wxworkDeviceProductEnum = WxworkDeviceProductEnum.getValue(deviceWxworkInfoAddProbationAuth.getProductCode());

        if (wxworkDeviceProductEnum == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该产品不存在");
        }

        List<String> productCodeList = JSONObject.parseArray(wxworkDeviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置该产品信息");
        }

        //业务编码
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

        //当前时间
        int now = DateUtil.getNowTime();
        //产品到期时间=当前时间+5天
        int expired_time = now + Const.Device.DEVICE_DAT_FREE_DURATION.intValue() * 24 * 3600;

        //新增加时，只能买全包，计算是否需要补差价
        for (String productCode : productCodeList) {

            DeviceAuth deviceAuth_old = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWxworkInfo.getDeviceId(), productCode);
            if (deviceAuth_old != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该产品已经有授权记录，不能增加试用期授权");
            }

            //添加机器人授权表
            DeviceAuth deviceAuth = new DeviceAuth();
            deviceAuth.setId(IdWorker.getId());
            deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceAuth.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            deviceAuth.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
            deviceAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
            deviceAuth.setProductCode(productCode);
            //新授权，到期时间从今天开始算
            deviceAuth.setExpireTime(expired_time);
            deviceAuth.setCreateTime(now);
            deviceAuth.setUpdateTime(now);
            deviceAuthMapper.insert(deviceAuth);

            //封装设备产品授权记录明细
            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
            deviceAuthDetail.setId(IdWorker.getId());
            deviceAuthDetail.setMerId(merId);
            deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
            deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
            deviceAuthDetail.setProductCode(productCode);
            deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
            deviceAuthDetail.setQuantity(0); //试用为0
            deviceAuthDetail.setPayTime(now);
            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
            deviceAuthDetail.setTradeno(trandeNo);
            deviceAuthDetail.setRemark("手动试用期授权");
            deviceAuthDetail.setCreateTime(now);
            deviceAuthDetail.setUpdateTime(now);
            deviceAuthDetail.setAmount(0.00);
            deviceAuthDetail.setBeginTime(now);
            deviceAuthDetail.setExpireTime(expired_time);
            //插入授权数据明细
            deviceAuthDetailMapper.insert(deviceAuthDetail);
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该机器人的所有产品授权信息
        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
        deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }

            Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
            if (object != null) { //修改
                DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoWxWorkCacheDto.class);
                if (deviceInfoWxWorkCacheDto != null) {
                    deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                    //更新企业微信机器人redis
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
                }
            } else {//新增
                DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = new DeviceInfoWxWorkCacheDto();
                deviceInfoWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
                deviceInfoWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
                deviceInfoWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                deviceInfoWxWorkCacheDto.setMsgHandler(DeviceTypeEnum.DT_WORK_WECHAT_VALUE); //接收消息
                //更新PC端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
            }
        }

    }

    /**
     * 转移授权时间
     *
     * @param deviceWxworkInfoTranferAuthTimeDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void transferAuthTime(DeviceWxworkInfoTranferAuthTimeDto deviceWxworkInfoTranferAuthTimeDto) {

        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

        int now = DateUtil.getNowTime();
        Long merId = deviceWxworkInfoTranferAuthTimeDto.getMerId();

        Long id = deviceWxworkInfoTranferAuthTimeDto.getId();
        Long transferIdForAuthTime = deviceWxworkInfoTranferAuthTimeDto.getTransferIdForAuthTime();
        Long transferIdForUserAndOrder = deviceWxworkInfoTranferAuthTimeDto.getTransferIdForUserAndOrder();
        Integer transferDataFlag = deviceWxworkInfoTranferAuthTimeDto.getTransferDataFlag();

        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择被转移机器人");
        }
        if (transferIdForAuthTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择新转移授权时间机器人");
        }

        if (id.longValue() == transferIdForAuthTime.longValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoTranferAuthTimeDto.getMerId());
        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移机器人不存在");
        }

        DeviceWxworkInfo deviceWxworkInfo_transferForAuthTime = deviceWxworkInfoMapper.selectById(transferIdForAuthTime, deviceWxworkInfoTranferAuthTimeDto.getMerId());
        if (deviceWxworkInfo_transferForAuthTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移授权时间机器人不存在");
        }

        //查询被转机器人的授权记录
        //授权信息
        List<DeviceAuthVo> deviceAuthVoList = new ArrayList<>();
        DeviceAuthQuery deviceAuthQuer = new DeviceAuthQuery();
        deviceAuthQuer.setDeviceId(deviceWxworkInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuer);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //到期时间
                Integer expiretime = Tools.getInteger(deviceAuth.getExpireTime());
                //计算出将要转移的时间（授权时间减去5天试用期）
                int transferTime = expiretime.intValue() - now - 5 * 24 * 3600;
                if (expiretime.intValue() > now && transferTime > 0) { //未到期有授权、且授权时间大于5天后（授权时间需要减去5天试用期）才能转移
                    //先将被转机器人的授权修改成现在到期
                    deviceAuth.setExpireTime(now);
                    deviceAuthMapper.updateById(deviceAuth);

                    //添加授权记录
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(merId);
                    deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceAuth.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceAuth.getDeviceType());
                    deviceAuthDetail.setDeviceTypeId(deviceAuth.getDeviceTypeId());
                    deviceAuthDetail.setProductCode(deviceAuth.getProductCode());
                    deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                    deviceAuthDetail.setQuantity(0);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                    deviceAuthDetail.setTradeno(trandeNo);
                    deviceAuthDetail.setRemark("机器人转移（转出），新机器人微信id:=" + deviceWxworkInfo_transferForAuthTime.getDeviceId() + ";旧授权时间:=" + expiretime + ";转移时间:=" + transferTime);
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetail.setAmount(0.00);
                    deviceAuthDetail.setBeginTime(now);
                    deviceAuthDetail.setExpireTime(deviceAuth.getExpireTime());
                    //插入授权数据明细
                    deviceAuthDetailMapper.insert(deviceAuthDetail);


                    //然后将新转移机器人的授权时间延长
                    DeviceAuth deviceAuth_transfer = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWxworkInfo_transferForAuthTime.getDeviceId(), deviceAuth.getProductCode());
                    //先判断存不存在，不存在则新增，存在则延迟时间
                    if (deviceAuth_transfer != null) { //授权存在，还需要判断授权时间是否过去
                        Integer expireTime_transfer = Tools.getInteger(deviceAuth_transfer.getExpireTime());

                        //未过期，则直接添加授权时间插
                        if (expireTime_transfer - now > 0) {
                            deviceAuth_transfer.setExpireTime(expireTime_transfer.intValue() + transferTime);
                            deviceAuth_transfer.setUpdateTime(now);
                            deviceAuthMapper.updateById(deviceAuth_transfer);

                            //添加授权记录
                            DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                            deviceAuthDetail_transfer.setId(IdWorker.getId());
                            deviceAuthDetail_transfer.setMerId(merId);
                            deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                            deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                            deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                            deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                            deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                            deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                            deviceAuthDetail_transfer.setQuantity(0);
                            deviceAuthDetail_transfer.setPayTime(now);
                            deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                            deviceAuthDetail_transfer.setTradeno(trandeNo);
                            deviceAuthDetail_transfer.setRemark("机器人转移（转入），旧机器人微信id:=" + deviceWxworkInfo.getDeviceId() + ";旧授权时间:=" + expireTime_transfer + ";转移时间:=" + transferTime);
                            deviceAuthDetail_transfer.setCreateTime(now);
                            deviceAuthDetail_transfer.setUpdateTime(now);
                            deviceAuthDetail_transfer.setAmount(0.00);
                            deviceAuthDetail_transfer.setBeginTime(now);
                            deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);

                        } else {//已过期，则直接将被转移机器人的授权到期时间减去5天试用期，替换新机器人的授权到期时间
                            deviceAuth_transfer.setExpireTime(expiretime - 5 * 24 * 3600);
                            deviceAuth_transfer.setUpdateTime(now);
                            deviceAuthMapper.updateById(deviceAuth_transfer);

                            //添加授权记录
                            DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                            deviceAuthDetail_transfer.setId(IdWorker.getId());
                            deviceAuthDetail_transfer.setMerId(merId);
                            deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                            deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                            deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                            deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                            deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                            deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                            deviceAuthDetail_transfer.setQuantity(0);
                            deviceAuthDetail_transfer.setPayTime(now);
                            deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                            deviceAuthDetail_transfer.setTradeno(trandeNo);
                            deviceAuthDetail_transfer.setRemark("机器人转移，旧机器人微信id:=" + deviceWxworkInfo.getDeviceId() + ";旧授权时间:=" + expireTime_transfer + ";转移时间:=" + transferTime);
                            deviceAuthDetail_transfer.setCreateTime(now);
                            deviceAuthDetail_transfer.setUpdateTime(now);
                            deviceAuthDetail_transfer.setAmount(0.00);
                            deviceAuthDetail_transfer.setBeginTime(now);
                            deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);
                        }
                    } else { //不存在
                        deviceAuth_transfer = new DeviceAuth();
                        deviceAuth_transfer.setId(IdWorker.getId());
                        deviceAuth_transfer.setDeviceId(deviceWxworkInfo_transferForAuthTime.getDeviceId());
                        deviceAuth_transfer.setDeviceUniqueId(deviceWxworkInfo_transferForAuthTime.getId());
                        deviceAuth_transfer.setDeviceType(DeviceTypeEnum.DT_WORK_WECHAT.getKey());
                        deviceAuth_transfer.setDeviceTypeId(DeviceTypeEnum.DT_WORK_WECHAT.getId());
                        deviceAuth_transfer.setProductCode(deviceAuth.getProductCode());
                        deviceAuth_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                        //将被转移机器人的授权到期时间减去5天试用期，替换新机器人的授权到期时间
                        deviceAuth_transfer.setExpireTime(expiretime - 5 * 24 * 3600);
                        deviceAuth_transfer.setCreateTime(now);
                        deviceAuth_transfer.setUpdateTime(now);
                        deviceAuthMapper.insertSelective(deviceAuth_transfer);

                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                        deviceAuthDetail_transfer.setId(IdWorker.getId());
                        deviceAuthDetail_transfer.setMerId(merId);
                        deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                        deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                        deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                        deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                        deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                        deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                        deviceAuthDetail_transfer.setQuantity(0);
                        deviceAuthDetail_transfer.setPayTime(now);
                        deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                        deviceAuthDetail_transfer.setTradeno(trandeNo);
                        deviceAuthDetail_transfer.setRemark("机器人转移，旧机器人微信id:" + deviceWxworkInfo.getDeviceId() + ";旧授权时间:=0;转移时间:=" + transferTime);
                        deviceAuthDetail_transfer.setCreateTime(now);
                        deviceAuthDetail_transfer.setUpdateTime(now);
                        deviceAuthDetail_transfer.setAmount(0.00);
                        deviceAuthDetail_transfer.setBeginTime(now);
                        deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);
                    }
                }
            }
        }

        //刷新新转移机器人的授权缓存
        flashDeviceAuth(deviceWxworkInfo_transferForAuthTime);

        //增加新机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWxworkInfo_transferForAuthTime.getDeviceId(), deviceWxworkInfo_transferForAuthTime.getRecvmsgType());
        //删除旧机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWxworkInfo.getDeviceId());

        //转移会员和订单
        if (transferDataFlag != null && transferDataFlag.intValue() == 1) {
            if (transferIdForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择新转移会员订单机器人");
            }

            DeviceWxworkInfo deviceWxworkInfo_transferForUserAndOrder = deviceWxworkInfoMapper.selectById(transferIdForUserAndOrder, deviceWxworkInfoTranferAuthTimeDto.getMerId());
            if (deviceWxworkInfo_transferForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单机器人不存在");
            }

            if (id.longValue() == transferIdForUserAndOrder.longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
            }

            ConfigPlan configPlan_self = configPlanMapper.selectById(deviceWxworkInfo.getConfigId(), deviceWxworkInfo.getMerId());
            if (configPlan_self == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移的机器人配置方案不存在");
            }

            ConfigPlan configPlan_transferForUserAndOrder = configPlanMapper.selectById(deviceWxworkInfo_transferForUserAndOrder.getConfigId(), deviceWxworkInfo_transferForUserAndOrder.getMerId());
            if (configPlan_transferForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人配置方案不存在");
            }

            if (Tools.getLong(configPlan_self.getUserTypeGroupId()).longValue() != Tools.getLong(configPlan_transferForUserAndOrder.getUserTypeGroupId()).longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人的会员类型组与旧的不一样");
            }

            //转移会员
            wxworkUserMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
        }
    }

    /**
     * 刷新企业微信机器人授权信息
     *
     * @param deviceWxworkInfo
     * @return null
     * @author jitwxs
     * @date 2023/8/17 15:47
     */
    public void flashDeviceAuth(DeviceWxworkInfo deviceWxworkInfo, List<DeviceAuth> deviceAuthList) {
        if (deviceWxworkInfo == null) {
            return;
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }
        }

        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        if (object_pc != null) { //修改
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoWxWorkCacheDto.class);
            if (deviceInfoWxWorkCacheDto != null) {
                deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                //更新企业微信机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
            }
        } else {//新增
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = new DeviceInfoWxWorkCacheDto();
            deviceInfoWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
            deviceInfoWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceInfoWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
            deviceInfoWxWorkCacheDto.setMsgHandler(DeviceTypeEnum.DT_WORK_WECHAT_VALUE); //接收消息
            if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId()) { //PC端接收消息
                deviceInfoWxWorkCacheDto.setMsgHandler(1); //接收消息
            } else {
                deviceInfoWxWorkCacheDto.setMsgHandler(0); //不接受消息
            }
            //更新PC端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
        }

        //更新移动端redis
        Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        if (object_moblie != null) { //修改
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWxWorkCacheDto.class);
            if (deviceInfoMobileWxWorkCacheDto != null) {
                deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));

        } else {
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = new DeviceInfoMobileWxWorkCacheDto();
            deviceInfoMobileWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
            deviceInfoMobileWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceInfoMobileWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()) { //手机端接收消息
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
        }


    }

    /**
     * 刷新企业微信机器人授权信息
     *
     * @param deviceWxworkInfo
     * @return null
     * @author jitwxs
     * @date 2023/8/17 15:47
     */
    public void flashDeviceAuth(DeviceWxworkInfo deviceWxworkInfo) {
        if (deviceWxworkInfo == null) {
            return;
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该机器人的所有产品授权信息
        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
        deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }
        }

        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        if (object_pc != null) { //修改
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoWxWorkCacheDto.class);
            if (deviceInfoWxWorkCacheDto != null) {
                deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
                //更新企业微信机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
            }
        } else {//新增
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = new DeviceInfoWxWorkCacheDto();
            deviceInfoWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
            deviceInfoWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceInfoWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceInfoWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            deviceInfoWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
            deviceInfoWxWorkCacheDto.setMsgHandler(DeviceTypeEnum.DT_WORK_WECHAT_VALUE); //接收消息
            //更新PC端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
        }

        //更新移动端redis
        Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        if (object_moblie != null) { //修改
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWxWorkCacheDto.class);
            if (deviceInfoMobileWxWorkCacheDto != null) {
                deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
                deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));

        } else {
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = new DeviceInfoMobileWxWorkCacheDto();
            deviceInfoMobileWxWorkCacheDto.setMerId(deviceWxworkInfo.getMerId());
            deviceInfoMobileWxWorkCacheDto.setDeviceId(deviceWxworkInfo.getDeviceId());
            deviceInfoMobileWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()) { //手机端接收消息
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
        }

    }

    /**
     * 修改工作状态
     *
     * @param deviceWxworkRecvmsgTypeDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateRecvmsgType(DeviceWxworkRecvmsgTypeDto deviceWxworkRecvmsgTypeDto) {
        if (deviceWxworkRecvmsgTypeDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkRecvmsgTypeDto.getId(), deviceWxworkRecvmsgTypeDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

//        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
//        deviceAuthQuery.setDeviceId(deviceWxworkInfo.getDeviceId());
//        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
//        if (deviceAuthList == null || deviceAuthList.size() == 0) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该端还未任何产品授权，不能切换");
//        }

        //工作状态值列表
        List<Integer> recvmsgTypeList = Lists.newArrayList(2, 9);
        if (!recvmsgTypeList.contains(Tools.getInteger(deviceWxworkRecvmsgTypeDto.getRecvmsgType()))) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "输入的工作状态值有误");
        }

        //修改个人微信机器人信息
        Integer now = DateUtil.getNowTime();
        deviceWxworkInfo.setRecvmsgType(deviceWxworkRecvmsgTypeDto.getRecvmsgType());
        deviceWxworkInfo.setUpdateTime(now);
        deviceWxworkInfoMapper.updateByIdSelective(deviceWxworkInfo);

        if (deviceWxworkRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId()) { //PC端接收消息
            //则将PC端授权卡密设置成到期
            //查询该设备微信id是否已经授权，如果存在，则需要将到期日修改成过期
//            CdkeysMobileApp cdkeysMobileApp = cdkeysMobileAppMapper.selectByDeviceId(deviceWxworkInfo.getDeviceId());
//            if(cdkeysMobileApp != null) {//存在，表示已经授权过，刷新授权即可
//                cdkeysMobileApp.setExpireTime(now);
//                cdkeysMobileApp.setUpdateTime(now);
//                int i = cdkeysMobileAppMapper.updateById(cdkeysMobileApp);
//                if (i != 1) {
//                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络繁忙，请稍后再试");
//                }
//            }

            //删除该机器人的授权
            deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWxworkInfo.getDeviceId());

        } else {
//            DeviceAuth deviceAuth = deviceAuthMapper.selectLastAuthByDeviceId(deviceWxworkInfo.getDeviceId());
//            if (deviceAuth != null) {
                //异步执行给机器人移动端APP授权
                String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWxworkInfo.getDeviceId(), deviceWxworkInfo.getRecvmsgType());
//            }
        }

        //发送切换设备端指令
//        MsgDto msgDto = new MsgDto<>();
//        msgDto.setContent("");
//        msgDto.setId(IdWorker.getId());
//        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
//        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
//        msgDto.setMerId(deviceWxworkInfo.getMerId());
//        msgDto.setMsgType(MessageFuncEnum.CHANGE_DEVICE_MSG_HANDER.getValue());
//        noticeMsgPushProducerService.sendDeviceMsgHander(msgDto);

        //修改redis
        //获取PC端cache,如果有，则修改
        Object cache_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()));
        if (cache_pc != null) {
            DeviceInfoWxWorkCacheDto deviceInfoWxWorkCacheDto = JSONObject.parseObject(String.valueOf(cache_pc), DeviceInfoWxWorkCacheDto.class);
            if (deviceInfoWxWorkCacheDto != null) {
                if (deviceWxworkRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_WORK_WECHAT.getId()) { //PC端接收消息
                    deviceInfoWxWorkCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoWxWorkCacheDto.setMsgHandler(0);
                }
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoWxWorkCacheDto)));
            }
        }

        //获取移动端cache,如果有，则修改
        Object cache_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        if (cache_mobile != null) {
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(cache_mobile), DeviceInfoMobileWxWorkCacheDto.class);
            if (deviceInfoMobileWxWorkCacheDto != null) {
                if (deviceWxworkRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()) { //手机端接收消息
                    deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
                }
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
            }
        }
    }

    /**
     * 修改工作状态
     *
     * @param deviceWxworkRecvmsgTypeBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchUpdateRecvmsgType(DeviceWxworkRecvmsgTypeBatchDto deviceWxworkRecvmsgTypeBatchDto){
        List<Long> idList = deviceWxworkRecvmsgTypeBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            try {
                DeviceWxworkRecvmsgTypeDto deviceWxworkRecvmsgTypeDto = new DeviceWxworkRecvmsgTypeDto();
                deviceWxworkRecvmsgTypeDto.setMerId(deviceWxworkRecvmsgTypeBatchDto.getMerId());
                deviceWxworkRecvmsgTypeDto.setId(id);
                deviceWxworkRecvmsgTypeDto.setRecvmsgType(deviceWxworkRecvmsgTypeBatchDto.getRecvmsgType());
                updateRecvmsgType(deviceWxworkRecvmsgTypeDto);
            }catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 更新手机版
     *
     * @param deviceWxworkInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateMobileClientSoft(DeviceWxworkInfoIdDto deviceWxworkInfoIdDto) {
        if (deviceWxworkInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(deviceWxworkInfoIdDto.getId(), deviceWxworkInfoIdDto.getMerId());

        if (deviceWxworkInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //从缓存中换取企业微信移动端信息
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWxWorkCacheDto.class);

        //移动端企业微信信息不为空
        if (deviceInfoMobileWxWorkCacheDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "移动端机器人还未曾登录过，不能更新版本");
        }

        //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
        Integer updateClientVersionStatus = deviceInfoMobileWxWorkCacheDto.getUpdateClientVersionStatus();
        Integer updateClientVersionTime = deviceInfoMobileWxWorkCacheDto.getUpdateClientVersionTime();
        if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
            if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人版本正在更新中 ，请稍后再试");
            }
        }

//        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());
//        if(deviceVersion == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人最新版本为空");
//        }

        //从缓存中获取版本移动端版本信息
        Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.WXWORK_MOBILE_APP_UPDATE_INFO.getKey());
        if (object_mobile_version == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息未设置");
        }

        JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
        if (jsonObject == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息格式错误");
        }

        //软件版本号
        Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
        //软件版本名称
        String version = Tools.getStr(jsonObject.getString("version"));
        //包名称
        String packageName = Tools.getStr(jsonObject.getString("packageName"));
        //软件包URL地址
        String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));

        //发送微服务，通知终端
        MsgDto<UpdateAndroidAppDto> msgDto = new MsgDto<>();
        UpdateAndroidAppDto updateAndroidAppDto = new UpdateAndroidAppDto();
        msgDto.setContent(updateAndroidAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.UPDATE_ANDROID_APP.getValue());
        //封装参数对象
        updateAndroidAppDto.setWechatId(deviceWxworkInfo.getDeviceId());
        updateAndroidAppDto.setImei(deviceWxworkInfo.getDeviceId());
        updateAndroidAppDto.setVerNumber(verNumber);
        updateAndroidAppDto.setVersion(version);
        updateAndroidAppDto.setPackageName(packageName);
        updateAndroidAppDto.setPackageUrl(packageUrl);
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.androidAppUpdate(msgDto);
        logger.info("---调用企业微信安卓APP版本更新接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
            //修改Redis状态
            deviceInfoMobileWxWorkCacheDto.setUpdateClientVersionStatus(2);
            deviceInfoMobileWxWorkCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
        }

    }

    /**
     * 批量更新手机版
     *
     * @param deviceWxworkInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchUpdateMobileClientSoft(DeviceWxworkInfoIdListDto deviceWxworkInfoIdListDto) {

        List<Long> idList = deviceWxworkInfoIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        for (Long id : idList) {
            DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectById(id, deviceWxworkInfoIdListDto.getMerId());
            if (deviceWxworkInfo == null) {
                continue;
            }

            //从缓存中换取个人微信手机版端信息
            Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWxWorkCacheDto.class);

            //手机版个人微信信息不为空
            if (deviceInfoMobileWxWorkCacheDto == null) {
                continue;
            }

            //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
            Integer updateClientVersionStatus = deviceInfoMobileWxWorkCacheDto.getUpdateClientVersionStatus();
            Integer updateClientVersionTime = deviceInfoMobileWxWorkCacheDto.getUpdateClientVersionTime();
            if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
                if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                    continue;
                }
            }

//            DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());
//            if(deviceVersion == null){
//                continue;
//            }

            //调用微服务通知移动端APP更新
            try {
                //从缓存中获取版本移动端版本信息
                Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.WXWORK_MOBILE_APP_UPDATE_INFO.getKey());
                if (object_mobile_version == null) {
                    continue;
                }

                JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
                if (jsonObject == null) {
                    continue;
                }

                //软件版本号
                Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
                //软件版本名称
                String version = Tools.getStr(jsonObject.getString("version"));
                //包名称
                String packageName = Tools.getStr(jsonObject.getString("packageName"));
                //软件包URL地址
                String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));

                //发送微服务，通知终端
                MsgDto<UpdateAndroidAppDto> msgDto = new MsgDto<>();
                UpdateAndroidAppDto updateAndroidAppDto = new UpdateAndroidAppDto();
                msgDto.setContent(updateAndroidAppDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
                msgDto.setMerId(deviceWxworkInfo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.UPDATE_ANDROID_APP.getValue());
                //封装参数对象
                updateAndroidAppDto.setWechatId(deviceWxworkInfo.getDeviceId());
                updateAndroidAppDto.setImei(deviceWxworkInfo.getDeviceId());
                updateAndroidAppDto.setVerNumber(verNumber);
                updateAndroidAppDto.setVersion(version);
                updateAndroidAppDto.setPackageName(packageName);
                updateAndroidAppDto.setPackageUrl(packageUrl);
                UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.androidAppUpdate(msgDto);
                logger.info("---调用企业微信安卓APP版本更新接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    //修改Redis状态
                    deviceInfoMobileWxWorkCacheDto.setUpdateClientVersionStatus(2);
                    deviceInfoMobileWxWorkCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 添加机器人信息，创建订单
     *
     * @param deviceWxworkInfoAddDto_new
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void addDeviceWxworkInfo_new(DeviceWxworkInfoAddDto_new deviceWxworkInfoAddDto_new) {

        //查询账号信息
        Merchant merchant = merchantMapper.selectById(deviceWxworkInfoAddDto_new.getMerId());
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
        }

        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        Integer now = DateUtil.getNowTime();
        Integer expired_time = now;
        Long merId = deviceWxworkInfoAddDto_new.getMerId();

        //机器人类型id
        Integer deviceTypeId = deviceWxworkInfoAddDto_new.getDeviceTypeId();
        if (deviceTypeId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型id");
        }

        if (deviceTypeId.intValue() != DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持添加企业微信机器人移动端");
        }

        //机器人类型key
        String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

        //机器人wxid
        String deviceId = deviceWxworkInfoAddDto_new.getDeviceId();
        if (StringUtils.isBlank(deviceId)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人wxid");
        }

        if(deviceId.length() != 16){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "wxid不正确，只支持16位wxid");
        }

        boolean flag = StringUtils.isNumeric(deviceId);
        if (!flag) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "wxid不正确，只支持纯数字");
        }

        //选择该运营商默认配置方案
        ConfigPlan configPlan = configPlanMapper.selectByIsDefault(deviceWxworkInfoAddDto_new.getMerId(), deviceTypeKey);
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商没有默认的配置方案");
        }

        //查询整个数据库当中正在使用的该微信id
        DeviceWxworkInfo deviceWxworkInfo = deviceWxworkInfoMapper.selectByDeviceId(deviceId);
        //有在使用的机器人
        if (deviceWxworkInfo != null) {
            //该机器人不属于自己运营商，则提示错误
            if (deviceWxworkInfo.getMerId().longValue() != deviceWxworkInfoAddDto_new.getMerId().longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信ID已经被其他运营商使用");
            }
        }

        //添加机器人只能试用全包套餐
        DeviceProduct deviceProduct_add = deviceProductMapper.selectByCode(DeviceProductEnum.ALL.getValue());
        if (deviceProduct_add == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置全包套餐");
        }

        //从枚举中获取关联的产品
        DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_add.getCode());
        List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统全包套餐还没配置包含产品信息");
        }

        //是否新增机器人
        if (deviceWxworkInfo == null) {//机器人为空，未还添加，则先添加机器人，默认配置方案
            //添加机器人
            deviceWxworkInfo = new DeviceWxworkInfo();
            deviceWxworkInfo.setId(IdWorker.getId());
            deviceWxworkInfo.setMerId(deviceWxworkInfoAddDto_new.getMerId());
            deviceWxworkInfo.setDeviceId(deviceWxworkInfoAddDto_new.getDeviceId());
            deviceWxworkInfo.setConfigId(configPlan.getId());
            deviceWxworkInfo.setRecvmsgType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId());//企业微信移动端
            deviceWxworkInfo.setConfigRule(0); //用户默认客户端
            deviceWxworkInfo.setRefreshWxcontactsTime(0); //刷新通讯录时间
            deviceWxworkInfo.setCreateTime(now);
            deviceWxworkInfo.setUpdateTime(now);
            //添加机器人
            deviceWxworkInfoMapper.insert(deviceWxworkInfo);

            //选择该运营商默认配置方案，需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
            if (configPlan.getOtherId() != null) {
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWxworkInfoAddDto_new.getMerId());
                if (sysPlugin != null) {
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWxworkInfo.getId()), sysPlugin.getData());
                }
            }
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该设备id是否已经授权过，如果没有，则开通试用期授权
        DeviceAuth deviceAuth_last = deviceAuthMapper.selectLastAuthByDeviceId(deviceId);
        if (deviceAuth_last == null) {//未开通过授权，则开通试用期权限
            expired_time = now + 5 * 24 * 3600;
            //新增加时，只能买全包，计算是否需要补差价
            for (String productCode : productCodeList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceProductAuth.setExpireTime(expired_time);
                deviceProductAuth.setProductCode(productCode);
                deviceProductAuthList.add(deviceProductAuth);

                //封装设备产品授权记录明细
                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                deviceAuthDetail.setId(IdWorker.getId());
                deviceAuthDetail.setMerId(merId);
                deviceAuthDetail.setDeviceUniqueId(deviceWxworkInfo.getId());
                deviceAuthDetail.setDeviceId(deviceWxworkInfo.getDeviceId());
                deviceAuthDetail.setDeviceType(deviceTypeKey);
                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                deviceAuthDetail.setProductCode(productCode);
                deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceAuthDetail.setQuantity(0); //试用为0
                deviceAuthDetail.setPayTime(now);
                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                deviceAuthDetail.setTradeno(trandeNo);
                deviceAuthDetail.setRemark("试用期");
                deviceAuthDetail.setCreateTime(now);
                deviceAuthDetail.setUpdateTime(now);
                deviceAuthDetail.setAmount(0.00);
                deviceAuthDetail.setBeginTime(now);
                deviceAuthDetail.setExpireTime(expired_time);
                //插入授权数据明细
                deviceAuthDetailMapper.insert(deviceAuthDetail);

                //添加机器人授权表
                DeviceAuth deviceAuth = new DeviceAuth();
                deviceAuth.setId(IdWorker.getId());
                deviceAuth.setDeviceId(deviceWxworkInfo.getDeviceId());
                deviceAuth.setDeviceUniqueId(deviceWxworkInfo.getId());
                deviceAuth.setDeviceType(deviceTypeKey);
                deviceAuth.setDeviceTypeId(deviceTypeId);
                deviceAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceAuth.setProductCode(productCode);
                //新授权，到期时间从今天开始算
                deviceAuth.setExpireTime(expired_time);
                deviceAuth.setCreateTime(now);
                deviceAuth.setUpdateTime(now);
                deviceAuthMapper.insert(deviceAuth);
            }
            //异步执行给机器人移动端APP授权
            deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWxworkInfo.getDeviceId(), deviceWxworkInfo.getRecvmsgType());
        } else {
            //刷新旧授权
            DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
            deviceAuthQuery.setDeviceId(deviceId);
            List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
            if (deviceAuthList != null && deviceAuthList.size() > 0) {
                for (DeviceAuth deviceAuth : deviceAuthList) {
                    //机器人redis缓存信息-产品授权
                    DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                    deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                    deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                    deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                    deviceProductAuthList.add(deviceProductAuth);
                }
            }

            //刷新授权APP信息
            expired_time = deviceAuth_last.getExpireTime();
            if (expired_time > now) { //授权未到期，则重新刷新授权APP信息
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceId, deviceWxworkInfo.getRecvmsgType());
            }
        }

        //添加redis缓存-机器人所属运营商
        Merchant device_merchant = new Merchant();
        device_merchant.setId(merchant.getId());
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWxworkInfo.getDeviceId()), Tools.getStrEmpty(JSONObject.toJSONString(device_merchant)));

        //发送切换设备端指令
        MsgDto msgDto = new MsgDto<>();
        msgDto.setContent("");
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWxworkInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWxworkInfo.getId());
        msgDto.setMerId(deviceWxworkInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CHANGE_DEVICE_MSG_HANDER.getValue());
        noticeMsgPushProducerService.sendDeviceMsgHander(msgDto);

        //更新机器人redis
        Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()));
        if (object != null) {//修改运营商信息
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoMobileWxWorkCacheDto.class);
            if (deviceInfoMobileWxWorkCacheDto != null) {
                deviceInfoMobileWxWorkCacheDto.setMerId(merId);
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
            }
        } else {
            DeviceInfoMobileWxWorkCacheDto deviceInfoMobileWxWorkCacheDto = new DeviceInfoMobileWxWorkCacheDto();
            deviceInfoMobileWxWorkCacheDto.setMerId(merId);
            deviceInfoMobileWxWorkCacheDto.setDeviceId(deviceId);
            deviceInfoMobileWxWorkCacheDto.setDeviceUniqueId(deviceWxworkInfo.getId());
            deviceInfoMobileWxWorkCacheDto.setConfigId(deviceWxworkInfo.getConfigId());
            deviceInfoMobileWxWorkCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWxworkInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT.getId()) { //企业微信手机端接收消息
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWxWorkCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WXWORK_MOBLE.getKey(), deviceWxworkInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWxWorkCacheDto)));
        }

    }

}
